package com.hmdp.interceptor;

import com.alibaba.fastjson.JSON;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 续签拦截器
 * 拦截所有请求，有权限则续签，无权登录拦截器处理
 *
 * @author leizi
 * @date 2024/03/10
 */
@Slf4j
public class BeforeInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public BeforeInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 拦截所有请求，校验权限续期
        log.info("BeforeInterceptor request url:{}", request.getRequestURI());
        String token = request.getHeader("authorization");
        // 无权限放开，登录拦截器处理
        if (StringUtils.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }
        String userCache = redisTemplate.opsForValue().get(RedisConstants.LOGIN_USER_KEY + token);
        if (StringUtils.isEmpty(userCache)) {
            response.setStatus(401);
            return false;
        }
        // 续签token
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 登录用户存入当前线程
        UserDTO userDTO = JSON.parseObject(userCache, UserDTO.class);
        UserHolder.saveUser(userDTO);

        return true;
    }
}
